package org.classg.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.classg.order.entity.Order;
import org.classg.order.entity.PayLog;
import org.classg.order.mapper.PayLogMapper;
import org.classg.order.service.OrderService;
import org.classg.order.service.PayLogService;
import org.classg.order.utils.ConstantPropertiesUtil;
import org.classg.order.utils.HttpClient;
import org.classg.servicebase.exception.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-06-16
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    private OrderService orderService;

    // 根据订单号生成微信支付二维码
    @Override
    public Map<String, Object> queryPaymentCodeByOrderNo(String orderNo) {
        // 根据订单号获取订单信息
        try {
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
            Map<String, String> m1 = new HashMap<>();
            // 设置支付参数
            m1.put("appid", ConstantPropertiesUtil.WEIXIN_PAY_APP_ID);
            m1.put("mch_id", ConstantPropertiesUtil.WEIXIN_PAY_PARTNET);
            m1.put("nonce_str", WXPayUtil.generateNonceStr());
            m1.put("body", order.getCourseTitle()); //课程标题
            m1.put("out_trade_no", orderNo); //订单号
            m1.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            m1.put("spbill_create_ip", "127.0.0.1");
            m1.put("notify_url", ConstantPropertiesUtil.WEIXIN_PAY_NOTIFY_URL);
            m1.put("trade_type", "NATIVE");
            // 发送httpclient请求，传递参数xml格式，微信支付是固定的地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            // 设置xml格式的参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m1, ConstantPropertiesUtil.WEIXIN_PAY_PARTNER_KEY));
            client.setHttps(true);
            // 执行post请求发送
            client.post();

            // 返回第三方数据
            String contentXML = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(contentXML);
            // 封装返回结果集
            Map<String, Object> map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));  //返回二维码操作状态码
            map.put("code_url", resultMap.get("code_url"));        //二维码地址
            return map;
        } catch (Exception e) {
            throw new MyException(20001, "生成微信支付二维码失败！");
        }
    }

    // 根据订单号获取支付状态
    @Override
    public Map<String, String> queryPayStatusByOrderNo(String orderNo) {
        try {
            // 1. 封装数据
            Map<String, String> map = new HashMap<>();
            map.put("appid", ConstantPropertiesUtil.WEIXIN_PAY_APP_ID);
            map.put("mch_id", ConstantPropertiesUtil.WEIXIN_PAY_PARTNET);
            map.put("out_trade_no", orderNo);
            map.put("nonce_str", WXPayUtil.generateNonceStr());

            // 2. 设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(map, ConstantPropertiesUtil.WEIXIN_PAY_PARTNER_KEY));
            client.setHttps(true);
            client.post();

            // 3. 返回第三方的数据
            String contentXML = client.getContent();
            return WXPayUtil.xmlToMap(contentXML);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 更新订单状态
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        String orderNo = map.get("out_trade_no");
        // 根据订单号查询订单信息
        Order order = orderService.queryOrderByOrderNo(orderNo);
        if (order.getStatus().intValue() == 1) return;
        order.setStatus(1);
        orderService.updateById(order);

        // 添加支付日志（添加支付记录和更新订单状态）
        PayLog payLog = new PayLog();
        payLog.setOrderNo(order.getOrderNo());
        payLog.setPayTime(new Date());
        payLog.setTotalFee(order.getTotalFee());// 总金额
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setTradeState(map.get("trade_state"));// 支付状态
        payLog.setPayType(1);// 支付类型
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);
    }
}
